package com.oniontech.stamptour;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager.BackStackEntry;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.client.android.CaptureActivity;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.oniontech.stamptour.common.Task.ContentsListQuery;
import com.oniontech.stamptour.common.adapter.Bean.ContentsListBean;
import com.oniontech.stamptour.common.adapter.StampContListAdapter;
import com.oniontech.stamptour.common.ui.CustomDialog;
import com.oniontech.stamptour.common.ui.DefaultActivity;
import com.oniontech.stamptour.common.util.SharedPreperenceUtil;
import com.oniontech.stamptour.fragment.app.StampMainFragment;
import com.oniontech.stamptour.fragment.app.StampMainToListFragment;
import com.oniontech.stamptour.fragment.app.WebViewFragmentContDetail;
import com.oniontech.stamptour.fragment.app.WebViewFragmentInfo;
import com.oniontech.stamptour.fragment.listener.FragmentListener;
import com.oniontech.stamptour.fragment.listener.QueryListener;
import com.oniontech.stamptour.module.encryption.CryptString;
import com.oniontech.stamptour.module.gps.MyLocation;
import com.oniontech.stamptour.module.gps.MyLocation.LocationResult;
import com.oniontech.stamptour.module.nfc.StampNfcManager;

import java.util.List;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

// TODO: Auto-generated Javadoc

/**
 * The Class MainActivity.
 */
public class MainActivity extends DefaultActivity implements FragmentListener,
        OnBackStackChangedListener {
    private final static int TITLE_INFO = R.string.tit_info;
    /**
     * The Constant FRAGMENT_REPLACE.
     */
    public final static int FRAGMENT_REPLACE = 0;

    /**
     * The Constant FRAGMENT_ADD.
     */
    public final static int FRAGMENT_ADD = 1;

    /**
     * The Constant FRAGMENT_ADD_NO_ANIM.
     */
    public final static int FRAGMENT_ADD_NO_ANIM = 3;

    /**
     * The Constant FRAGMENT_REPLACE_NO_STACK.
     */
    public final static int FRAGMENT_REPLACE_NO_STACK = 2;

    /**
     * The Constant REQ_QR.
     */
    public final static int REQ_QR = 4;

    /**
     * QR.
     */
    public final static int QR = 3;

    /**
     * The ft.
     */
    private FragmentTransaction ft;

    /**
     * The main fragment.
     */
    private Fragment mainFragment = null;

    private CustomDialog dialog, gpsdialog = null;
    // 2회 클릭 시 종료
    /**
     * The back press close handler.
     */
//    private BackPressCloseHandler backPressCloseHandler = null;

    /**
     * The now fragment.
     */
    private Fragment nowFragment = null;

    /**
     * The vg.
     */
    private ViewGroup vg;

    /**
     * The tab my.
     */
    private Button tabHome, tabQR, tabInfo;

    private StampNfcManager stampNfcManager = null;
    private String m_url = null;

    private ContentsListBean contentsBean = null;

    /**
     * Instantiates a new main activity.
     */
    public MainActivity() {
        super(MainActivity.class.getSimpleName());
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        vg = (ViewGroup) inflater.inflate(R.layout.activity_main, null);
        setContentView(vg);

        dialog = new CustomDialog(this);
        dialog.setDialogTitle(getResources().getString(R.string.app_info));
        dialog.setDialogMsg(getResources().getString(R.string.app_txt));
        dialog.setBtnText("종료", "아니오");
        dialog.setCustomDialog(click, true);
//        backPressCloseHandler = new BackPressCloseHandler(this);

		/* 2차 추가 : 하단 탭 */
        tabHome = (Button) findViewById(R.id.tabHome);
        tabQR = (Button) findViewById(R.id.tabQR);
        tabInfo = (Button) findViewById(R.id.tabInfo);

        tabHome.setOnClickListener(tabListener);
        tabQR.setOnClickListener(tabListener);
        tabInfo.setOnClickListener(tabListener);

        contentsBean = new ContentsListBean();

        mainFragment = new StampMainFragment();
        setFragment(mainFragment, FRAGMENT_REPLACE);

        stampNfcManager = new StampNfcManager(this);
        stampNfcManager.onNewIntent(getIntent(), nfcCompleteListener);

        if(!SharedPreperenceUtil.getInstance().getBooleanValue("GPS","gps")) {
            gpsdialog = new CustomDialog(this);
            gpsdialog.setDialogTitle(getResources().getString(R.string.app_info));
            gpsdialog.setDialogMsg(getResources().getString(R.string.gps_txt));
            gpsdialog.setBtnText("동의하지 않음", "동의 함");
            gpsdialog.setCancelable(false);
            gpsdialog.setCustomDialog(gpsclick, true);
            gpsdialog.Show();
        }

    }

    private OnClickListener gpsclick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case CustomDialog.BTN_CONFIRM:
                    gpsdialog.Dismiss();
                    finish();
                    break;

                case CustomDialog.BTN_CANCEL:
                    gpsdialog.Dismiss();
                    SharedPreperenceUtil.getInstance().setBooleanValue("GPS","gps",true);
                    break;
            }
        }
    };

    private StampNfcManager.NfcCompleteListener nfcCompleteListener = new StampNfcManager.NfcCompleteListener() {
        @Override
        public void getPayload(String payload) {

        }

        @Override
        public void getContKey(String key) {
            m_url = key;
            startGPS();
        }
    };

    private OnClickListener click = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case CustomDialog.BTN_CANCEL:
                    dialog.Dismiss();
                    break;

                case CustomDialog.BTN_CONFIRM:
                    dialog.Dismiss();
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        stampNfcManager.onNewIntent(intent, nfcCompleteListener);
    }

    public void moveHome() {

        setNavStatus(new StampMainFragment());

        int count = getSupportFragmentManager().getBackStackEntryCount();
        for (int idx = count; idx > 0; idx--) {
            Fragment fragment = getNowFragment(idx);
            if (!(fragment instanceof StampMainFragment))
                getSupportFragmentManager().popBackStack();
            else
                break;
        }

    }

    /**
     * The tab listener.
     */
    private View.OnClickListener tabListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Fragment fragment = null;

            switch (v.getId()) {
                case R.id.tabHome:
                    moveHome();

                    break;

                case R.id.tabQR:
                    callQR();

                    break;

                case R.id.tabInfo:
                    int i = getSupportFragmentManager().getBackStackEntryCount();
                    Fragment nowFragment = getNowFragment(i);

                    if (nowFragment instanceof WebViewFragmentInfo)
                        return;

                    fragment = new WebViewFragmentInfo();
                    ((WebViewFragmentInfo) fragment).onFragmentData("file:///android_asset/img/info.png");
                    setFragment(fragment, MainActivity.FRAGMENT_ADD);
                    break;

            }
        }
    };

    /**
     * Call qr.
     */
    public void callQR() {
        Intent intent = new Intent().setClass(m_AppContext,
                CaptureActivity.class);
        startActivityForResult(intent, REQ_QR);
    }

    /**
     * The m location.
     */
    protected MyLocation m_Location;
    /**
     * The progress bar.
     */
    private ProgressDialog progressBar = null;
    // private Double lat, lon;

    /**
     * Location 정보 값.
     */

    LocationResult locationResult = new LocationResult() {

        @Override
        public void gotLocation(Location location, String provider) {
            // TODO Auto-generated method stub
            // lat = location.getLatitude();
            // lon = location.getLongitude();

            Log.i("Main", " 제공자 = " + provider + "\n" + "위도 = " + location.getLatitude() + "\n경도 = " + location.getLongitude());

            if (provider.equals("gps")) {
                progressBar.dismiss();
                m_Location.dispos();


                Log.i("Main", " 제공자 = " + provider + "\n" + "위도 = " + location.getLatitude() + "\n경도 = " + location.getLongitude());

                if (cheCkStamp()) {

                    float[] results = new float[2];

                    Location.distanceBetween((double) contentsBean.getLat(), (double) contentsBean.getLon(),
                            location.getLatitude(), location.getLongitude(),
    //                        37.554444, 127.102887,
                            results);

                    Log.i("GPSDATA", String.format(
                            "lat : [%f] lon : [%f] rad : [%f], [%f]",
                            location.getLatitude(), location.getLongitude(),
                            results[0], contentsBean.getRad()));

                    if ((int) results[0] < (int) contentsBean.getRad()) {

    //                    setUpdateDB(contentsBean.getId());
                        setUpdateDB(contentsBean.getId());
                        ((StampMainFragment) mainFragment).setMainIcon();

                        int i = getSupportFragmentManager().getBackStackEntryCount();
                        for (int idx = 0; idx < i; idx++) {
                            Fragment fragment = getNowFragment(idx);
                            if (fragment != null) {
                                if (fragment instanceof StampMainToListFragment) {
                                    ((StampMainToListFragment) fragment).reflash();
                                } else if (fragment instanceof WebViewFragmentContDetail) {

                                }
                            }
                        }


                        final CustomDialog makedialog = new CustomDialog(MainActivity.this);
                        makedialog.setDialogTitle(getResources().getString(
                                R.string.app_info));
                        makedialog.setDialogMsg(getResources().getString(
                                R.string.GPS_OK));
                        makedialog.setCancelable(false);
                        makedialog.setBtnText("확인", "다시시도");
                        makedialog.setCustomDialog(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // TODO Auto-generated method stub
                                switch (v.getId()) {
                                    case R.id.btn_dial_confirm:
                                        new ContentsListQuery(contentsBean.getTheme_code(), contentsBean.getId(), new QueryListener() {
                                            @Override
                                            public void queryComplete(Object data) {
                                                List<ContentsListBean> list = (List<ContentsListBean>) data;
                                                Fragment fragment = new WebViewFragmentContDetail();
                                                ((WebViewFragmentContDetail) fragment).onFragmentData(list.get(0));
                                                setFragment(fragment, MainActivity.FRAGMENT_ADD);
                                                makedialog.Dismiss();
                                            }
                                        }).execute();

                                        break;
                                }
                            }
                        }, false);

                        makedialog.Show();

                    } else {
                        final CustomDialog makedialog = new CustomDialog(MainActivity.this);
                        makedialog.setDialogTitle(getResources().getString(
                                R.string.app_info));
                        makedialog.setDialogMsg(getResources().getString(
                                R.string.GPS_FAIL));
                        makedialog.setCancelable(false);
                        makedialog.setBtnText("다시시도", "다시시도");
                        makedialog.setCustomDialog(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // TODO Auto-generated method stub
                                switch (v.getId()) {
                                    case R.id.btn_dial_confirm:
                                        callQR();
                                        makedialog.Dismiss();
                                        break;

                                    case R.id.btn_dial_cancel:
                                        // 설정
                                        callQR();
                                        makedialog.Dismiss();
                                        break;
                                }
                            }
                        }, false);

                        makedialog.Show();

                    }


                } else {

                    final CustomDialog makedialog = new CustomDialog(MainActivity.this);
                    makedialog.setDialogTitle(getResources().getString(
                            R.string.app_info));
                    makedialog.setDialogMsg(getResources().getString(
                            R.string.GPS_FAIL));
                    makedialog.setCancelable(false);
                    makedialog.setBtnText("다시시도", "다시시도");
                    makedialog.setCustomDialog(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            switch (v.getId()) {
                                case R.id.btn_dial_confirm:
                                    callQR();
                                    makedialog.Dismiss();
                                    break;

                                case R.id.btn_dial_cancel:
                                    // 설정
                                    callQR();
                                    makedialog.Dismiss();
                                    break;
                            }
                        }
                    }, false);

                    makedialog.Show();

                }
            }

        }
    };

    public Boolean cheCkStamp() {
        m_DBMgr.openPointDB(DB_TYPE_ADDRESS, true);

        String str = null;

        StringBuffer sb = new StringBuffer();

        sb.append("SELECT theme_code,id,name,lon,lat,rad,url FROM contents where id = '" + parsingId() + "'\n");

        Cursor cursor = m_DBMgr.DBQuery(sb.toString());

        if (cursor == null || !cursor.moveToFirst()) {
            m_DBMgr.closeDB();
            return false;
        }

        int cnt = cursor.getCount();

        if (cnt == 0) {

            return false;
        }

        for (int i = 0; i < cnt; i++) {
            contentsBean.setTheme_code(cursor.getString(cursor.getColumnIndex("theme_code")));
            contentsBean.setId(cursor.getString(cursor.getColumnIndex("id")));
            contentsBean.setName(cursor.getString(cursor.getColumnIndex("name")));
            contentsBean.setLon(cursor.getFloat(cursor.getColumnIndex("lon")));
            contentsBean.setLat(cursor.getFloat(cursor.getColumnIndex("lat")));
            contentsBean.setRad(cursor.getFloat(cursor.getColumnIndex("rad")));
            contentsBean.setUrl(cursor.getString(cursor.getColumnIndex("url")));

            Log.i(TAG, "+++++++++++++++++++  인식됨!!!!!!!!! : "+ contentsBean.getName());

            cursor.moveToNext();
        }

        cursor.close();
        m_DBMgr.closeDB();

        return true;
    }

    public String parsingId() {
        int start = m_url.indexOf("VdkVgwKey=") + 10;
        m_url = m_url.substring(start);

        return m_url;
    }

    public Boolean setUpdateDB(String themeCode) {

        m_DBMgr.openPointDB(DB_TYPE_ADDRESS, false);

        String str = null;

        StringBuffer sb = new StringBuffer();

        sb.append("update contents set visit = 1 where id='" + themeCode + "'\n");

        m_DBMgr.DBInsertQuery(sb.toString());
//        m_DBMgr.DBQuery(sb.toString());

        m_DBMgr.closeDB();

        return true;
    }


    /**
     * Start gps.
     */
    public void startGPS() {

//        LocationManager lm = (LocationManager) m_AppContext
//                .getSystemService(Context.LOCATION_SERVICE);
//
//        if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//            // gps 켜십시요!!!!! 안내 팝업
//
//            final CustomDialog makedialog = new CustomDialog(MainActivity.this);
//            makedialog.setDialogTitle(getResources().getString(
//                    R.string.app_info));
//            makedialog.setDialogMsg(getResources().getString(
//                    R.string.GPS_DIALOG_INFO));
//            makedialog.setBtnText("취소", "설정");
//            makedialog.setCustomDialog(new OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    // TODO Auto-generated method stub
//                    switch (v.getId()) {
//                        case R.id.btn_dial_confirm:
//                            makedialog.Dismiss();
//                            break;
//
//                        case R.id.btn_dial_cancel:
//                            // 설정
//                            showGpsOptions();
//                            makedialog.Dismiss();
//                            break;
//                    }
//                }
//            }, true);
//
//            makedialog.Show();
//
//            return;
//        }
        m_Location = MyLocation.getInstance();

        progressBar = ProgressDialog.show(this, "", "GPS 수신중입니다...", true,
                true, new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                m_Location.dispos();
                progressBar.dismiss();
            }
        });
        if (!m_Location.getLocation(getApplicationContext(), locationResult)) {
            progressBar.dismiss();

            final CustomDialog makedialog = new CustomDialog(MainActivity.this);
            makedialog.setDialogTitle(getResources().getString(
                    R.string.app_info));
            makedialog.setDialogMsg(getResources().getString(
                    R.string.GPS_DIALOG_INFO));
            makedialog.setBtnText("취소", "다시시도");
            makedialog.setCustomDialog(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    switch (v.getId()) {
                        case R.id.btn_dial_confirm:
                            makedialog.Dismiss();
                            break;

                        case R.id.btn_dial_cancel:
                            // 설정
                            callQR();
                            makedialog.Dismiss();
                            break;
                    }
                }
            }, true);

            makedialog.Show();
        }
    }

    /**
     * Show gps options.
     */
    public void showGpsOptions() {
        Intent intent = new Intent(
                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }

    /*
     * (non-Javadoc)
     *
     * @see android.support.v4.app.FragmentActivity#onActivityResult(int, int,
     * android.content.Intent)
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQ_QR:
                // qr 화면
                switch (resultCode) {

                    case RESULT_OK:

                        if (data == null){
                            final CustomDialog makedialog = new CustomDialog(MainActivity.this);
                            makedialog.setDialogTitle(getResources().getString(
                                    R.string.app_info));
                            makedialog.setDialogMsg(getResources().getString(
                                    R.string.QR_FAILED));
                            makedialog.setCancelable(false);
                            makedialog.setBtnText("다시시도", "다시시도");
                            makedialog.setCustomDialog(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    // TODO Auto-generated method stub
                                    switch (v.getId()) {
                                        case R.id.btn_dial_confirm:
                                            callQR();
                                            makedialog.Dismiss();
                                            break;

                                        case R.id.btn_dial_cancel:
                                            // 설정
                                            callQR();
                                            makedialog.Dismiss();
                                            break;
                                    }
                                }
                            }, false);

                            makedialog.Show();

                            return;
                        }

                        m_url = data.getStringExtra("QR");

//                        cheCkStamp();
                        startGPS();
                        break;

                    case RESULT_CANCELED:
                        break;
                }

                break;
        }
    }


    /**
     * Sets the fragment.
     *
     * @param fragment  the fragment
     * @param fragIdx   the frag idx
     * @param tabStatus the tab status
     */
    public void setFragment(Fragment fragment, int fragIdx, int tabStatus) {
        setFragment(fragment, fragIdx);
    }

    /**
     * Sets the fragment.
     *
     * @param fragment the fragment
     * @param fragIdx  the frag idx
     */
    public void setFragment(Fragment fragment, int fragIdx) {
        nowFragment = fragment;
        ft = getSupportFragmentManager().beginTransaction();
        switch (fragIdx) {
            case FRAGMENT_REPLACE:
                int backStackSize = getSupportFragmentManager()
                        .getBackStackEntryCount();
                for (int i = 0; i < backStackSize; i++) {
                    getSupportFragmentManager().popBackStack();
                }

                // - add 에서 replace 로 수정. error log :
                // java.lang.IllegalStateException: Fragment already added:
                // VoteListFragment
                ft.replace(R.id.viewScreen, fragment, ((Object) fragment).getClass()
                        .getSimpleName());
                ft.addToBackStack(((Object) fragment).getClass().getSimpleName());
                break;

            case FRAGMENT_ADD:
                ft.setCustomAnimations(R.anim.push_left_in_noalpha,
                        R.anim.push_right_out_noalpha,
                        R.anim.push_right_in_noalpha, R.anim.push_right_out_noalpha);
                ft.add(R.id.viewScreen, fragment, ((Object) fragment).getClass()
                        .getSimpleName());
                ft.addToBackStack(((Object) fragment).getClass().getSimpleName());
                break;

            case FRAGMENT_ADD_NO_ANIM:
                ft.add(R.id.viewScreen, fragment, ((Object) fragment).getClass()
                        .getSimpleName());
                ft.addToBackStack(((Object) fragment).getClass().getSimpleName());
                break;

            case FRAGMENT_REPLACE_NO_STACK:
                ft.replace(R.id.viewScreen, fragment);
                break;
        }
        ft.commit();

        setNavStatus(fragment);
    }

    /**
     * Sets the nav status.
     *
     * @param fragment the new nav status
     */
    public void setNavStatus(final Fragment fragment) {
        if (fragment instanceof StampMainFragment) {
            tabHome.setSelected(true);
            tabInfo.setSelected(false);
        } else if (fragment instanceof WebViewFragmentInfo) {
            tabHome.setSelected(false);
            tabInfo.setSelected(true);
        }else {
            tabHome.setSelected(false);
            tabInfo.setSelected(false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getSupportFragmentManager().addOnBackStackChangedListener(this);
        stampNfcManager.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stampNfcManager.onPause();
    }


    /*
     * (non-Javadoc)
     *
     * @see
     * com.oniontech.mvoting.fragment.listener.FragmentListener#onFragmentData
     * (java.lang.Object, android.support.v4.app.Fragment)
     */
    @Override
    public void onFragmentData(Object obj) {
    }

    /*
     * (non-Javadoc)
     *
     * @see android.support.v4.app.FragmentManager.OnBackStackChangedListener#
     * onBackStackChanged()
     */
    @Override
    public void onBackStackChanged() {
//        int i = getSupportFragmentManager().getBackStackEntryCount();
//
//        if (i > 0) {
//            setNavStatus(getNowFragment(i));
//        }
    }

    /*
     * (non-Javadoc)
     *
     * @see com.oniontech.mvoting.common.ui.DefaultActivity#onDestroy()
     */
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (m_Location != null) {
            m_Location.dispos();
        }
        m_appMgr.destroyMnager();
        super.onDestroy();
    }

    /**
     * Gets the now fragment.
     *
     * @param idx the idx
     * @return the now fragment
     */
    private Fragment getNowFragment(int idx) {
        BackStackEntry tt;
        Fragment currentFragment;

        if (idx == 0) {
            tt = getSupportFragmentManager().getBackStackEntryAt(idx);
            currentFragment = getSupportFragmentManager().findFragmentByTag(
                    tt.getName());

        } else {
            tt = getSupportFragmentManager().getBackStackEntryAt(idx - 1);
            currentFragment = getSupportFragmentManager().findFragmentByTag(
                    tt.getName());
        }

        return currentFragment;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.oniontech.mvoting.common.ui.DefaultActivity#onBackPressed()
     */
    @Override
    public void onBackPressed() {
        if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
            int i = getSupportFragmentManager().getBackStackEntryCount();
            final Fragment fragment = getNowFragment(i);
            // - 이것들 쓰는 코드임?
//			if (fragment instanceof SettingGroupFragment)
//			{
//				if (((SettingGroupFragment) fragment).m_nGroupState == SettingGroupFragment.GROUP_MAIN)
//				{
//					// dialog.Show();
//				} else
//				{
//					((SettingGroupFragment) fragment)
//							.backpressMode(((SettingGroupFragment) fragment).m_nGroupState);
//					return;
//				}
//			}
//			if (fragment instanceof StampMainFragment)
//			{
//				final CustomDialog makedialog = new CustomDialog(this);
//				makedialog.setDialogTitle(getResources().getString(
//						R.string.app_info));
//				makedialog.setDialogMsg(getResources().getString(
//						R.string.app_make_back1));
//				makedialog.setBtnText("취소", "확인");
//				makedialog.setCustomDialog(new OnClickListener()
//				{
//					@Override
//					public void onClick(View v)
//					{
//						// TODO Auto-generated method stub
//						switch (v.getId())
//						{
//						case R.id.btn_dial_confirm:
//							makedialog.Dismiss();
//							break;
//
//						case R.id.btn_dial_cancel:
//							// 끝내기
//							makedialog.Dismiss();
//							setFragment(new VoteListFragment(),
//									FRAGMENT_REPLACE);
//							break;
//						}
//					}
//				}, true);
//
//				makedialog.Show();
//				return;
//			} else if (!(fragment instanceof VoteListFragment))
//			{
//				setFragment(new VoteListFragment(), FRAGMENT_REPLACE);
//				return;
//			} else
//			{
//				dialog.Show();
////				backPressCloseHandler.onBackPressed();
//			}
            dialog.Show();
        } else {
			int i = getSupportFragmentManager().getBackStackEntryCount();
			final Fragment fragment = getNowFragment(i);
			if (i == 2) {
                setNavStatus(new StampMainFragment());
            }
            super.onBackPressed();
        }
    }
}
